﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class DepartmentDA : IDepartmentDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string DEPARTMENT_ID = "@DEPARTMENT_ID";
        private string DESCR = "@DESCR";
        private string DP_ADDRESS = "@DP_ADDRESS";
        private string DP_CONTACT = "@DP_CONTACT";
        private string DP_CONTACT_PHONE = "@DP_CONTACT_PHONE";
        private string DP_FAX = "@DP_FAX";
        private string DP_PHONE = "@DP_PHONE";
        private string IS_ACTIVE = "@IS_ACTIVE";
        private string PARENT_DP_ID = "@PARENT_DP_ID";
        private string REMARK = "@REMARK";
        private string SQL_CHECK_DEPARTMENT_ID_UNIQUE = " SELECT COUNT(1) FROM @_@DEPARTMENT WHERE DEPARTMENT_ID = @DEPARTMENT_ID ";
        private string SQL_DELETE_DEPARTMENT = " DELETE FROM @_@DEPARTMENT WHERE DEPARTMENT_ID = @DEPARTMENT_ID ";
        private string SQL_INSERT_DEPARTMENT = "INSERT INTO @_@DEPARTMENT(WH_ID,DEPARTMENT_ID,DESCR,DP_FAX,DP_PHONE,DP_ADDRESS,DP_CONTACT,DP_CONTACT_PHONE,PARENT_DP_ID,REMARK,IS_ACTIVE,CREATED_BY,CREATED_DATE,UPDATED_BY,UPDATED_DATE)VALUES(@WH_ID,@DEPARTMENT_ID,@DESCR,@DP_FAX,@DP_PHONE,@DP_ADDRESS,@DP_CONTACT,@DP_CONTACT_PHONE,@PARENT_DP_ID,@REMARK,@IS_ACTIVE,@CREATED_BY,GETDATE(),@UPDATED_BY,GETDATE())";
        private string SQL_SELECT_ALL_DEPARTMENT = "SELECT ROWID,WH_ID,DEPARTMENT_ID,DESCR,DP_FAX,DP_PHONE,DP_ADDRESS,DP_CONTACT,DP_CONTACT_PHONE,PARENT_DP_ID,REMARK,IS_ACTIVE,TS,CREATED_BY,CONVERT(VARCHAR(20),CREATED_DATE,23) AS CREATED_DATE,UPDATED_BY,UPDATED_DATE FROM @_@DEPARTMENT D";
        private string SQL_UPDATE_DEPARTMENT = " UPDATE @_@DEPARTMENT SET WH_ID = @WH_ID,DESCR = @DESCR,DP_FAX = @DP_FAX,DP_PHONE = @DP_PHONE,DP_ADDRESS = @DP_ADDRESS,DP_CONTACT = @DP_CONTACT, DP_CONTACT_PHONE = @DP_CONTACT_PHONE,PARENT_DP_ID =@PARENT_DP_ID,REMARK = @REMARK,IS_ACTIVE =@IS_ACTIVE,UPDATED_BY = @UPDATED_BY,UPDATED_DATE = GETDATE() WHERE DEPARTMENT_ID = @DEPARTMENT_ID";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string WH_ID = "@WH_ID";

        public bool CheckDepartmentIDUnique(string departmentID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DEPARTMENT_ID", departmentID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_DEPARTMENT_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckDepartmentIDUnique(DataBase dataBase, DbTransaction tran, string departmentID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DEPARTMENT_ID", departmentID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_DEPARTMENT_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteDepartment(List<string> departmentID, List<string> whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    for (int j = 0; j < departmentID.Count; j++)
                    {
                        SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DEPARTMENT_ID", departmentID[j]) };
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_DEPARTMENT.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteDepartment(DataBase dataBase, DbTransaction tran, List<string> departmentID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    for (int j = 0; j < departmentID.Count; j++)
                    {
                        SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DEPARTMENT_ID", departmentID[j]) };
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_DEPARTMENT.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllDepartment(string whLoginID, PubParasInfo pubParasInfo)
        {
            string sql = this.SQL_SELECT_ALL_DEPARTMENT.Replace("@_@", whLoginID);
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LANGUAGE", pubParasInfo.UserLanguage) };
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllDepartment(DataBase dataBase, DbTransaction tran, string whLoginID, PubParasInfo pubParasInfo)
        {
            string sql = this.SQL_SELECT_ALL_DEPARTMENT.Replace("@_@", whLoginID);
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LANGUAGE", pubParasInfo.UserLanguage) };
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public DepartmentInfo GetDepartmentByID(string departmentID, string whLoginID, PubParasInfo pubParasInfo)
        {
            string sql = this.SQL_SELECT_ALL_DEPARTMENT.Replace("@_@", whLoginID) + " WHERE DEPARTMENT_ID = @DEPARTMENT_ID ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DEPARTMENT_ID", departmentID), new SqlParameter("@LANGUAGE", pubParasInfo.UserLanguage) };
            DepartmentInfo departmentInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    departmentInfo = new DepartmentInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["DEPARTMENT_ID"].ToString(), reader["DESCR"].ToString(), reader["DP_PHONE"].ToString(), reader["DP_FAX"].ToString(), reader["DP_ADDRESS"].ToString(), reader["DP_CONTACT"].ToString(), reader["DP_CONTACT_PHONE"].ToString(), reader["PARENT_DP_ID"].ToString(), reader["REMARK"].ToString(), reader["IS_ACTIVE"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return departmentInfo;
        }

        public DepartmentInfo GetDepartmentByID(DataBase dataBase, DbTransaction tran, string departmentID, string whLoginID, PubParasInfo pubParasInfo)
        {
            string sql = this.SQL_SELECT_ALL_DEPARTMENT.Replace("@_@", whLoginID) + " WHERE DEPARTMENT_ID = @DEPARTMENT_ID ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DEPARTMENT_ID", departmentID), new SqlParameter("@LANGUAGE", pubParasInfo.UserLanguage) };
            DepartmentInfo departmentInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                departmentInfo = new DepartmentInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["DEPARTMENT_ID"].ToString(), reader["DESCR"].ToString(), reader["DP_PHONE"].ToString(), reader["DP_FAX"].ToString(), reader["DP_ADDRESS"].ToString(), reader["DP_CONTACT"].ToString(), reader["DP_CONTACT_PHONE"].ToString(), reader["PARENT_DP_ID"].ToString(), reader["REMARK"].ToString(), reader["IS_ACTIVE"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return departmentInfo;
        }

        public DataSet GetDepartmentByQueryList(List<string> sqlWhere, DepartmentQuerEntity departmentQuery, string whLoginID, PubParasInfo pubParasInfo)
        {
            string temp = this.SQL_SELECT_ALL_DEPARTMENT.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!departmentQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, departmentQuery.CurrentPage, departmentQuery.PageSize, departmentQuery.SortField, departmentQuery.SortDirection).Replace("@LANGUAGE", "''" + pubParasInfo.UserLanguage + "''");
            }
            else
            {
                temp = temp.Replace("@LANGUAGE", "'" + pubParasInfo.UserLanguage + "'");
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetDepartmentByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, DepartmentQuerEntity departmentQuery, string whLoginID, PubParasInfo pubParasInfo)
        {
            string temp = this.SQL_SELECT_ALL_DEPARTMENT.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!departmentQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, departmentQuery.CurrentPage, departmentQuery.PageSize, departmentQuery.SortField, departmentQuery.SortDirection).Replace("@LANGUAGE", "''" + pubParasInfo.UserLanguage + "''");
            }
            else
            {
                temp = temp.Replace("@LANGUAGE", "'" + pubParasInfo.UserLanguage + "'");
            }
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public int InsertDepartment(DepartmentInfo departmentInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    departmentInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Department_Parameters(departmentInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_DEPARTMENT.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertDepartment(DataBase dataBase, DbTransaction tran, DepartmentInfo departmentInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    departmentInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Department_Parameters(departmentInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_DEPARTMENT.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_Department_Parameters(DepartmentInfo departmentInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.WH_ID, SqlDbType.VarChar, 30), new SqlParameter(this.DEPARTMENT_ID, SqlDbType.VarChar, 100), new SqlParameter(this.DESCR, SqlDbType.VarChar, 300), new SqlParameter(this.DP_FAX, SqlDbType.VarChar, 30), new SqlParameter(this.DP_PHONE, SqlDbType.VarChar, 30), new SqlParameter(this.DP_ADDRESS, SqlDbType.VarChar, 30), new SqlParameter(this.DP_CONTACT, SqlDbType.VarChar, 30), new SqlParameter(this.DP_CONTACT_PHONE, SqlDbType.VarChar, 30), new SqlParameter(this.PARENT_DP_ID, SqlDbType.VarChar, 30), new SqlParameter(this.REMARK, SqlDbType.VarChar, 300), new SqlParameter(this.IS_ACTIVE, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 30), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 30) };
            if (!string.IsNullOrEmpty(departmentInfo.WhID))
            {
                paramArray[0].Value = departmentInfo.WhID;
            }
            else
            {
                paramArray[0].Value = DBNull.Value;
            }
            paramArray[1].Value = departmentInfo.DepartmentID;
            if (!string.IsNullOrEmpty(departmentInfo.Descr))
            {
                paramArray[2].Value = departmentInfo.Descr;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.DPFax))
            {
                paramArray[3].Value = departmentInfo.DPFax;
            }
            else
            {
                paramArray[3].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.DPPhone))
            {
                paramArray[4].Value = departmentInfo.DPPhone;
            }
            else
            {
                paramArray[4].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.DPAddress))
            {
                paramArray[5].Value = departmentInfo.DPAddress;
            }
            else
            {
                paramArray[5].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.DPContact))
            {
                paramArray[6].Value = departmentInfo.DPContact;
            }
            else
            {
                paramArray[6].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.DPContactPhone))
            {
                paramArray[7].Value = departmentInfo.DPContactPhone;
            }
            else
            {
                paramArray[7].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.ParentDpID))
            {
                paramArray[8].Value = departmentInfo.ParentDpID;
            }
            else
            {
                paramArray[8].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.Remark))
            {
                paramArray[9].Value = departmentInfo.Remark;
            }
            else
            {
                paramArray[9].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.IsActive))
            {
                paramArray[10].Value = departmentInfo.IsActive;
            }
            else
            {
                paramArray[10].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.CreatedBy))
            {
                paramArray[11].Value = departmentInfo.CreatedBy;
            }
            else
            {
                paramArray[11].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(departmentInfo.UpdatedBy))
            {
                paramArray[12].Value = departmentInfo.UpdatedBy;
                return paramArray;
            }
            paramArray[12].Value = DBNull.Value;
            return paramArray;
        }

        public int UpdateDepartment(DepartmentInfo departmentInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    departmentInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Department_Parameters(departmentInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_DEPARTMENT.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateDepartment(DataBase dataBase, DbTransaction tran, DepartmentInfo departmentInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    departmentInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Department_Parameters(departmentInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_DEPARTMENT.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

